package it.iubar.tkdscore;

import it.iubar.tkdscore.KeyMapping;
import it.iubar.tkdscore.TkdGlobal;
import it.iubar.tkdscore.TkdScoreApp;
import java.io.PrintStream;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.java.games.input.Component.Identifier.Key;
import net.java.games.input.ControllerEnvironment;
import net.java.games.input.Keyboard;
import net.java.games.input.Rumbler;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Controller;
//import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Controllers;
import org.lwjgl.util.Display;
import org.lwjgl.util.Timer;

/**
 *
 * @author borgo
 */
public class ControllersThread implements Runnable {

    static int numberOfControllers = 0;
    static int last_source = -1;
    static int last_button = -1;
    static ControllerTimeHashMap last_hit_time_map = new ControllerTimeHashMap();

    public static void init() {
        try {
            Controllers.create();
            numberOfControllers = Controllers.getControllerCount();
        } catch (LWJGLException ex) {
            Logger.getLogger(ControllersThread.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static boolean gameLoop() {
//        try {
//            Timer.tick();
//        } catch (Exception ex) {
//            Logger.getLogger(ControllersThread.class.getName()).log(Level.SEVERE, null, ex);
//        }

        try {
            Thread.sleep(Logic.POLLING_DELAY); // wait a while
        } catch (InterruptedException ex) {
            Logger.getLogger(ControllersThread.class.getName()).log(Level.SEVERE, null, ex);
        }

        // .. other logic/rendering here ..
        return true;
    }

    public static void check() {

        for (int i = 0; i < numberOfControllers; i++) {
            Controller playerControl = Controllers.getController(i);
            //int buttons = playerControl.getButtonCount();

            playerControl.poll(); // update the controller from the hardware

            // float currValue = c.getPollData(); // get current value


            // int selectedIndex = 0; // the index of the button we're checking
            //  if (playerControl.isButtonPressed(selectedIndex)) {
            //      TkdGlobal.print("Fired: " + selectedIndex + " - controller " + i);
            //  }

            //      for (int b = 0; b < buttons; b++) {
            //      if (playerControl.isButtonPressed(b)) {
            //          TkdGlobal.print("Fired: " + b);
            //      }
            //   }

        }

        while (Controllers.next()) {
            Controller source = Controllers.getEventSource();

            if (Controllers.isEventButton()) {
                String src_name = source.getName();
                int src_index = source.getIndex();
                int btn_index = Controllers.getEventControlIndex();

                System.out.println("Event button was from " + src_name + " (index " + src_index + ") and was from button " + btn_index);
                System.out.println("last_source = " + last_source + " last_button " + last_button);
                // if(!((src_index==last_source) && (btn_index==last_button))){

                long now_time = 0;
                long delta_last_click = 0;
                long last_time = 0;
                boolean bSkip = false;
                try {
                    now_time = (new Date()).getTime();
                    System.out.println("now_time: " + now_time);
                    last_time = last_hit_time_map.get(src_name, src_index);
                    System.out.println("last_time: " + last_time);
                    delta_last_click = now_time - last_time;
                    System.out.println("delta_last_click: " + delta_last_click);
                    last_hit_time_map.set(src_name, src_index, now_time);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                boolean bSamebutton = false;
                if ((last_source == src_index) && (last_button == btn_index)) {
                    bSamebutton = true;
                }

                if ((bSamebutton) && (delta_last_click < 200)) {
                    // ignore this. Clicks are counted always twice by the system
                    System.out.println("--> Event skipped because click was already counted | src_index = " + src_index + " | btn_index = " + btn_index + " | last_source = " + last_source + " | last_button = " + last_button);
                    bSkip = true;
                }

                if ((delta_last_click < Logic.MIN_CLICK_TIME_INTERVAL)) {
                    // delta_last_click = elapsed time of the last same button click
                    // MIN_CLICK_TIME_INTERVAL must be always greater than 200                  
                    System.out.println("--> Event skipped because click was too fast | src_index = " + src_index + " | btn_index = " + btn_index + " | last_source = " + last_source + " | last_button = " + last_button);
                    bSkip = true;
                }

                if (!bSkip) {

                    last_source = src_index;
                    last_button = btn_index;

                    if (btn_index == KeyMapping.CONFIG_LEFT_BOTTOM) {
                        TkdScoreApp.view.hitLeft(src_index, 1);
                    } else if (btn_index == KeyMapping.CONFIG_LEFT_TOP) {
                        TkdScoreApp.view.hitLeft(src_index, 2);
                    } else if (btn_index == KeyMapping.CONFIG_RIGHT_TOP) {
                        TkdScoreApp.view.hitRight(src_index, 2);
                    } else if (btn_index == KeyMapping.CONFIG_RIGHT_BOTTOM) {
                        TkdScoreApp.view.hitRight(src_index, 1);
                    } else {
                        System.out.println("button index not configured: " + btn_index);
                    }

                }

                //if((TkdGlobal.first_gamepad_index>-1) && (src_index==TkdGlobal.first_gamepad_index)){

                if (false) { //TODO: HERE

                    TkdScoreApp.view.clearTestLabels();
                    if (btn_index == KeyMapping.CONFIG_LEFT_BOTTOM) {
                        TkdScoreApp.view.setTestLabel(0, true);
                    } else if (btn_index == KeyMapping.CONFIG_LEFT_TOP) {
                        TkdScoreApp.view.setTestLabel(1, true);
                    } else if (btn_index == KeyMapping.CONFIG_RIGHT_BOTTOM) {
                        TkdScoreApp.view.setTestLabel(2, true);
                    } else if (btn_index == KeyMapping.CONFIG_RIGHT_TOP) {
                        TkdScoreApp.view.setTestLabel(3, true);
                    } else if (btn_index == KeyMapping.CONFIG_SHORTCUT_1) {
                        //TkdScoreApp.view.setTestLabel(3, true);
                        Logic.showBoard();
                    } else if (btn_index == KeyMapping.CONFIG_SHORTCUT_2) {
                        //TkdScoreApp.view.setTestLabel(3, true);
                        Logic.startTimer();
                    } else if (btn_index == KeyMapping.CONFIG_SHORTCUT_3) {
                        //TkdScoreApp.view.setTestLabel(3, true);
                        Logic.pauseTimer();
                    } else if (btn_index == KeyMapping.CONFIG_SHORTCUT_4) {
                        //TkdScoreApp.view.setTestLabel(3, true);
                        Logic.nextRound();
                    }


                }

            }
            if (Controllers.isEventAxis()) {
                System.out.println("Event axis was from " + source.getName() + " and was from axis " + Controllers.getEventControlIndex());
            }

            /*
            if (currValue != prevValue) { // the value has changed
            if (Math.abs(currValue) > EPSILON) {
            // only show values not near to 0.0f
            System.out.print(currValue + "; ");
            i++;
            }
            prevValue = currValue;
            }
             */

        } // end while

        Controllers.clearEvents();
    }

    @Override
    public void run() {

        TkdGlobal.print("numberOfControllers: " + numberOfControllers);
        for (int i = 0; i < numberOfControllers; i++) {
            Controller playerControl = Controllers.getController(i);



            int buttons = playerControl.getButtonCount();
            for (int b = 0; b < buttons; b++) {
                TkdGlobal.print("Button " + b + " = " + playerControl.getButtonName(b));
            }
        }

        while (gameLoop()) {

            check();

        }

    }
} // end class

